<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>系统后台</title>
    <script src="js/vue.min.js"></script>
    <script src="js/axios.min.js"></script>
    <!-- 引入 jQuery 库 -->
    <script src="./js/jquery-1.11.0.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
    <link href="css/root.css" rel="stylesheet">

</head>
<body>

<!-- Sidebar -->
<div class="sidebar">
    <h2 class="ftype1">管理员后台</h2>
    <h2 class="ftype2">用户后台</h2>
    <div class="button-returncontainer">
    </div>
    <ul>
        <li><a href="#" id="navAddCar">添加车辆</a></li>
        <li class="ftype"><a href="#" id="navViewCars">查看车辆</a></li>
        <li><a href="#" id="navUpdateCar">修改车辆</a></li>
        <li><a href="#" id="navDeleteCar">删除车辆</a></li>
        <li class="ftype"><a href="#" id="navDownloadData">下载数据</a></li>
        <li class="ftype"><a href="#" id="navUserManage">用户管理</a></li>
    </ul>
</div>

<!-- Main Content -->
<div class="main-content">
    <!-- Add Car Section -->
    <div class="section" id="addCarSection">
        <h1>添加车辆</h1>
        <!-- 单个添加表单 -->
        <!-- 单个添加表单 -->
        <form id="adminForm">
            <h3 class="form-subtitle">单个添加</h3>
            <label>车名：</label><input id="cname" name="cname" placeholder="请输入车名" required type="text"><br>
            <label>颜色：</label><input id="color" name="color" placeholder="请输入颜色" required type="text"><br>
            <label>价格：</label><input id="price" name="price" placeholder="请输入价格" required type="number"><br>
            <label>存储地点：</label><input id="storage" name="storage" placeholder="请输入存储地点" required
                                           type="text"><br>
            <label>状态：</label><input id="status" name="status" placeholder="状态" readonly type="text" value="未售出"><br>
            <label>创建人：</label><input id="creator" name="creator" placeholder="请输入创建人" required
                                         type="text"><br>
            <button type="submit">插入数据</button>
        </form>

        <!-- 批量上传部分 -->
        <div class="section" id="batchUploadSection">
            <h2 style="color: white">批量插入车辆数据</h2>
            <form id="batchUploadForm">
                <input accept=".txt,.csv" id="fileInput" type="file"/>
                <button type="submit">批量上传</button>
                <span id="fileName"></span>
            </form>
        </div>
    </div>

    <!-- View Cars Section -->
    <div class="section" id="viewCarsSection" style="display: none;">
        <h1>查看车辆</h1>
        <!-- ID查询表单 -->
        <div class="search-container">
            <input class="search-input" id="searchId" placeholder="输入车辆ID查询" type="number">
            <button class="search-btn" id="searchById">
                <i class="fas fa-search"></i> 查询
            </button>
        </div>

        <div class="button-container">
            <button id="querySoldCars">查看已售出车辆</button>
            <button id="queryUnsoldCars">查看未售出车辆</button>
            <button id="queryAllCars">查看所有车辆</button>
        </div>

        <!-- 查询结果显示区域 -->
        <div class="search-result" id="searchResult"></div>
        <div id="soldCars" style="display: none;"></div>
        <div id="unsoldCars" style="display: none;"></div>
        <div id="allCars" style="display: none;"></div>
    </div>


    <!-- Download Data Section -->
    <div class="section" id="downloadDataSection" style="display: none;">
        <h1>下载数据</h1>
        <div class="button-container">
            <button id="downloadSoldCarsCSV">下载 已售出 CSV</button>
            <button id="downloadSoldCarsTXT">下载 已售出 TXT</button>
            <button id="downloadUnsoldCarsCSV">下载 未售出 CSV</button>
            <button id="downloadUnsoldCarsTXT">下载 未售出 TXT</button>
            <button id="downloadAllCarsCSV">下载 全部 CSV</button>
            <button id="downloadAllCarsTXT">下载 全部 TXT</button>
        </div>
    </div>

    <!-- Update Car Section -->
    <div class="section" id="updateCarSection" style="display: none;">
        <h1>修改车辆</h1>
        <form id="updateForm">
            <label>车辆ID：</label><input id="cid" name="cid" placeholder="请输入车辆ID" required type="number"><br>
            <label>车名：</label><input id="updateCname" name="cname" placeholder="请输入新车名" required
                                       type="text"><br>
            <label>颜色：</label><input id="updateColor" name="color" placeholder="请输入新颜色" required
                                       type="text"><br>
            <label>价格：</label><input id="updatePrice" name="price" placeholder="请输入新价格" required
                                       type="number"><br>
            <label>状态：</label>
            <select id="updateStatus" required>
                <option value="0">未卖出</option>
                <option value="1">已卖出</option>
            </select><br>
            <button type="submit">更新数据</button>
        </form>
    </div>

    <!-- Delete Car Section -->
    <div class="section" id="deleteCarSection" style="display: none;">
        <h1>删除车辆</h1>
        <form id="deleteForm">
            <label>车辆ID：</label><input id="deleteCid" name="cid" placeholder="请输入车辆ID" required
                                         type="number"><br>
            <button type="submit">删除数据</button>
        </form>
    </div>

    <!-- 添加用户管理部分 -->
    <div class="section" id="userManageSection" style="display: none;">
        <h1>用户管理</h1>
        <div class="user-stats-container">
            <div class="user-stat-card">

                <div class="stat-info">
                    <h3>
                        <div class="stat-icon">
                            <i class="fas fa-user"></i>
                        </div>
                        普通用户
                        <div class="stat-number" id="normalUserCount">0</div>
                    </h3>

                    <button class="user-action-btn" onclick="toggleRegisterModal()">注册新用户</button>
                    <!-- 注册表单模态框 -->
                    <div id="registerModal" style="display: none;">
                        <h3 style="margin-top: 0;">注册新用户</h3>
                        <div style="margin-bottom: 10px;">
                            <label>账号名：</label>
                            <input id="unameInput" type="text">
                        </div>
                        <div style="margin-bottom: 15px;">
                            <label>密&nbsp;&nbsp;&nbsp;码：</label>
                            <input id="upassInput" type="password">
                        </div>
                        <div style="text-align: right;">
                            <button onclick="zhuce()">提交</button>
                            <button onclick="closeModal()">取消</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="user-stat-card">
                <div class="stat-info">
                    <h3>
                        <div class="stat-icon">
                            <i class="fas fa-user-shield"></i>
                        </div>
                        管理员用户
                        <div class="stat-number" id="adminUserCount">0</div>
                    </h3>

                    <button class="user-action-btn" onclick="toggleRegisterModalroot()">注册新用户</button>
                    <button class="user-action-btn" onclick="toggleManageModal()">管理用户</button>
                    <!-- 注册表单模态框 -->
                    <div id="registerModalroot" style="display: none;">
                        <h3 style="margin-top: 0;">注册新用户</h3>
                        <div style="margin-bottom: 10px;">
                            <label>账号名：</label>
                            <input id="rootunameInput" type="text">
                        </div>
                        <div style="margin-bottom: 15px;">
                            <label>密&nbsp;&nbsp;&nbsp;码：</label>
                            <input id="rootupassInput" type="password">
                        </div>
                        <div style="text-align: right;">
                            <button onclick="zhuceroot()">提交</button>
                            <button onclick="closeModalroot()">取消</button>
                        </div>
                    </div>
                    <!-- 管理表单模态框 -->
                    <div id="manageModal" style="display: none;">
                        <h3 style="margin-top: 0;">用户管理</h3>
                        <div style="margin-bottom: 10px;">
                            <label>用户ID：</label>
                            <input id="userIdInput" type="text">
                        </div>
                        <div style="margin-bottom: 10px;">
                            <label>用户名：</label>
                            <input id="userNameInput" type="text">
                        </div>
                        <div style="margin-bottom: 15px;">
                            <label>更改用户身份：</label>
                            <select id="userRootSelect">
                                <option value="1">管理员</option>
                                <option value="0">普通用户</option>
                            </select>
                        </div>
                        <div style="text-align: right;">
                            <button onclick="updateUser()">更改身份</button>
                            <button onclick="deleteUser()">删除用户</button>
                            <button onclick="closeManagelroot()">取消</button>
                        </div>
                    </div>

                </div>
            </div>
        </div>


        <div class="user-lists">
            <div class="user-list">
                <h3>普通用户列表</h3>
                <div class="user-table-container" id="normalUserList"></div>
            </div>
            <div class="user-list">
                <h3>管理员列表</h3>
                <div class="user-table-container" id="adminUserList"></div>
            </div>
        </div>
    </div>
</div>

<script>
    // 侧边栏导航控制显示不同的功能
    document.getElementById('navAddCar').onclick = function () {
        showSection('addCarSection');
    };
    document.getElementById('navViewCars').onclick = function () {
        showSection('viewCarsSection');
    };
    document.getElementById('navUpdateCar').onclick = function () {
        showSection('updateCarSection');
    };
    document.getElementById('navDeleteCar').onclick = function () {
        showSection('deleteCarSection');
    };
    document.getElementById('navDownloadData').onclick = function () {
        showSection('downloadDataSection');
    };
    document.getElementById('navUserManage').onclick = function () {
        showSection('userManageSection');
        fetchUserStats();
    };

    function showSection(sectionId) {
        const sections = document.querySelectorAll('.section');
        sections.forEach(section => section.style.display = 'none');
        document.getElementById(sectionId).style.display = 'block';
    }

    // 添加车辆
    document.getElementById('adminForm').onsubmit = function (event) {
        event.preventDefault();

        // 获取status值
        const status = document.getElementById('status').value;

        const car = {
            cname: document.getElementById('cname').value,
            color: document.getElementById('color').value,
            price: parseFloat(document.getElementById('price').value),
            storage: document.getElementById('storage').value,
            status: "未售出",
            creator: name
        };

        axios.post('/insertacar', car, {
            headers: {'User-Type': 'Admin'}
        }).then(response => alert("成功插入" + response.data + "条数据"))
            .catch(err => alert('错误: ' + err.response.data));
    };


    // 批量插入
    document.getElementById('fileInput').addEventListener('change', function (e) {
        const fileName = e.target.files[0]?.name || '未选择文件';
        document.getElementById('fileName').textContent = fileName;
    });

    document.getElementById('batchUploadForm').addEventListener('submit', function (e) {
        e.preventDefault();
        const file = document.getElementById('fileInput').files[0];
        if (!file) {
            alert('请选择文件');
            return;
        }

        const reader = new FileReader();
        reader.onload = function (e) {
            const content = e.target.result;
            const cars = parseFileContent(content, file.name);
            if (cars.length > 0) {
                uploadBatchData(cars);
            } else {
                alert('文件内容为空或格式不正确！');
            }
        };
        reader.readAsText(file, 'UTF-8'); // 明确指定编码为 UTF-8
    });

    function parseFileContent(content, fileName) {
        const cars = [];
        const lines = content.split('\n').filter(line => line.trim() !== '');
        const isCSV = fileName.toLowerCase().endsWith('.csv');

        lines.forEach((line, index) => {
            if (index === 0 && isCSV) return;

            let data;
            if (isCSV) {
                data = line.split(',');
            } else {
                data = line.match(/ID: (\d+), 车名: (.+), 颜色: (.+), 价格: (\d+), 数量: (\d+), 存储地点: (.+), 时间: (\d{4}-\d{2}-\d{2}), 状态: (.+), 创建人: (.+)/);
                if (data) {
                    data = data.slice(1);
                }
            }

            if (data && data.length >= 9) {
                cars.push({
                    cid: parseInt(data[0]),
                    cname: data[1],
                    color: data[2],
                    price: parseFloat(data[3]),
                    storage: data[4],
                    status: "未售出", // 固定值
                    creator: name // 从URL参数中获取的uname
                });
            }
        });

        return cars;
    }

    function uploadBatchData(cars) {
        axios.post('/insertcarall', cars, {
            headers: {'User-Type': 'Admin'}
        })
            .then(response => {
                alert(`成功批量插入${response.data}条数据`);
                document.getElementById('fileInput').value = ''; // 清空文件选择
                document.getElementById('fileName').textContent = ''; // 清空文件名显示
            })
            .catch(err => {
                alert('批量上传失败: ' + (err.response?.data || err.message));
            });
    }


    // 更新车辆
    document.getElementById('updateForm').onsubmit = function (event) {
        event.preventDefault();
        const car = {
            cid: parseInt(document.getElementById('cid').value),
            cname: document.getElementById('updateCname').value,
            color: document.getElementById('updateColor').value,
            price: parseFloat(document.getElementById('updatePrice').value),
            status: parseInt(document.getElementById('updateStatus').value)
        };
        axios.post('/updatecar', car, {
            headers: {'User-Type': 'Admin'}
        }).then(response => alert(response.data))
            .catch(err => alert('错误: ' + err.response.data));
    };


    // 删除车辆
    document.getElementById('deleteForm').onsubmit = function (event) {
        event.preventDefault();
        const cid = parseInt(document.getElementById('deleteCid').value);
        axios.delete('/deletecar', {
            params: {cid: cid},
            headers: {'User-Type': 'Admin'}
        }).then(response => alert(response.data))
            .catch(err => alert('错误: ' + err.response.data));
    };

    // 通过ID查询功能
    document.getElementById('searchById').addEventListener('click', function () {
        const id = document.getElementById('searchId').value;
        if (!id) {
            alert('请输入车辆ID');
            return;
        }

        axios.get(`/selectacar?cid=${id}`, {
            headers: {'User-Type': 'Admin'}
        })
            .then(response => {
                const cars = response.data;
                if (cars && cars.length > 0) {
                    const car = cars[0]; // 取数组中的第一个元素
                    const resultHtml = `
                    <div class="search-result-item">
                        <h4>查询结果</h4>
                        <p>ID: ${car.cid}</p>
                        <p>车名: ${car.cname}</p>
                        <p>颜色: ${car.color}</p>
                        <p>价格: ${car.price}</p>
                        <p>状态: ${car.status}</p>
                        ${car.time ? `<p>售出/入库时间: ${car.time}</p>` : ''}
                    </div>
                `;
                    document.getElementById('searchResult').innerHTML = resultHtml;
                } else {
                    document.getElementById('searchResult').innerHTML = `
                    <div class="search-result-item error">
                        未找到对应车辆信息
                    </div>
                `;
                }
            })
            .catch(err => {
                document.getElementById('searchResult').innerHTML = `
                <div class="search-result-item error">
                    请求失败，请稍后重试
                </div>
            `;
            });
    });


    // 查询已售出车辆
    let soldCarsData = [];
    let unsoldCarsData = [];
    let allCarsData = [];

    // 查询已售出车辆
    document.getElementById('querySoldCars').onclick = function () {
        axios.get('/sselectcarall', {
            headers: {'User-Type': 'Admin'}
        }).then(response => {
            soldCarsData = response.data;
            let soldCarsHtml = "<h3>已售出车辆：</h3><ul>";
            soldCarsData.forEach(car => {
                soldCarsHtml += `<li>id: ${car.cid}, 车名: ${car.cname}, 颜色: ${car.color}, 价格: ${car.price}, 时间: ${car.time}, 状态: 已售出</li>`;
            });
            soldCarsHtml += "</ul>";
            document.getElementById('soldCars').innerHTML = soldCarsHtml;

            // 显示已售出车辆，隐藏未售出车辆
            document.getElementById('soldCars').style.display = 'block';
            document.getElementById('unsoldCars').style.display = 'none';
            document.getElementById('allCars').style.display = 'none';

        }).catch(err => alert('错误: ' + err.response.data));
    };

    // 查询未售出车辆
    document.getElementById('queryUnsoldCars').onclick = function () {
        axios.get('/unselectcarall', {
            headers: {'User-Type': 'Admin'}
        }).then(response => {
            unsoldCarsData = response.data;
            let unsoldCarsHtml = "<h3>未售出车辆：</h3><ul>";
            unsoldCarsData.forEach(car => {
                unsoldCarsHtml += `<li>id: ${car.cid}, 车名: ${car.cname}, 颜色: ${car.color}, 价格: ${car.price}, 时间: ${car.time}, 状态: 未售出</li>`;
            });
            unsoldCarsHtml += "</ul>";
            document.getElementById('unsoldCars').innerHTML = unsoldCarsHtml;

            // 显示未售出车辆，隐藏已售出车辆
            document.getElementById('unsoldCars').style.display = 'block';
            document.getElementById('soldCars').style.display = 'none';
            document.getElementById('allCars').style.display = 'none';
        }).catch(err => alert('错误: ' + err.response.data));
    };

    //查询所有车辆
    document.getElementById('queryAllCars').onclick = function () {
        axios.get('/selectcarall', {
            headers: {'User-Type': 'Admin'}
        }).then(response => {
            allCarsData = response.data;
            let AllCarsHtml = "<h3>所有车辆：</h3><ul>";
            allCarsData.forEach(car => {
                AllCarsHtml += `<li>id: ${car.cid}, 车名: ${car.cname}, 颜色: ${car.color}, 价格: ${car.price}, 时间: ${car.time}, 状态: <span style="color: white">${car.status}</span></li>`;
            });
            AllCarsHtml += "</ul>";
            document.getElementById('allCars').innerHTML = AllCarsHtml;

            // 显示未售出车辆，隐藏已售出车辆
            document.getElementById('allCars').style.display = 'block';
            document.getElementById('unsoldCars').style.display = 'none';
            document.getElementById('soldCars').style.display = 'none';
        }).catch(err => alert('错误: ' + err.response.data));
    };


    // 下载已售出车辆的CSV文件
    document.getElementById('downloadSoldCarsCSV').onclick = function () {
        if (soldCarsData.length === 0) {
            alert("请先查询已售出车辆！");
            return;
        }

        // 创建CSV内容
        const csvContent = "\uFEFFID,车名,颜色,价格,存储地点,时间,状态,创建人\n" +
            soldCarsData.map(car =>
                `${car.cid},${car.cname},${car.color},${car.price},${car.storage || ''},${car.time || ''},已售出,${car.creator || ''}`
            ).join("\n");

        // 创建 Blob 对象
        const blob = new Blob([csvContent], {type: "text/csv;charset=utf-8"});
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = "已售出车辆数据.csv";
        link.click();
    };

    // 下载已售出车辆的TXT文件
    document.getElementById('downloadSoldCarsTXT').onclick = function () {
        if (soldCarsData.length === 0) {
            alert("请先查询已售出车辆！");
            return;
        }

        // 创建 TXT 内容
        const txtContent = soldCarsData.map(car =>
            `ID: ${car.cid}, 车名: ${car.cname}, 颜色: ${car.color}, 价格: ${car.price}, 存储地点: ${car.storage || ''}, 时间: ${car.time || ''}, 状态: 已售出, 创建人: ${car.creator || ''}`
        ).join("\n");

        // 创建 Blob 对象
        const blob = new Blob([txtContent], {type: "text/plain;charset=utf-8"});
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = "已售出车辆数据.txt";
        link.click();
    };

    // 下载未售出车辆的CSV文件
    document.getElementById('downloadUnsoldCarsCSV').onclick = function () {
        if (unsoldCarsData.length === 0) {
            alert("请先查询未售出车辆！");
            return;
        }

        // 创建CSV内容
        const csvContent = "\uFEFFID,车名,颜色,价格,存储地点,时间,状态,创建人\n" +
            unsoldCarsData.map(car =>
                `${car.cid},${car.cname},${car.color},${car.price},${car.storage || ''},${car.time || ''},未售出,${car.creator || ''}`
            ).join("\n");

        // 创建 Blob 对象
        const blob = new Blob([csvContent], {type: "text/csv;charset=utf-8"});
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = "未售出车辆数据.csv";
        link.click();
    };

    // 下载未售出车辆的TXT文件
    document.getElementById('downloadUnsoldCarsTXT').onclick = function () {
        if (unsoldCarsData.length === 0) {
            alert("请先查询未售出车辆！");
            return;
        }

        // 创建 TXT 内容
        const txtContent = unsoldCarsData.map(car =>
            `ID: ${car.cid}, 车名: ${car.cname}, 颜色: ${car.color}, 价格: ${car.price}, 存储地点: ${car.storage || ''}, 时间: ${car.time || ''}, 状态: 未售出, 创建人: ${car.creator || ''}`
        ).join("\n");

        // 创建 Blob 对象
        const blob = new Blob([txtContent], {type: "text/plain;charset=utf-8"});
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = "未售出车辆数据.txt";
        link.click();
    };

    // 下载全部车辆的CSV文件
    document.getElementById('downloadAllCarsCSV').onclick = function () {
        if (allCarsData.length === 0) {
            alert("请先查询所有车辆！");
            return;
        }

        // 创建CSV内容
        const csvContent = "\uFEFFID,车名,颜色,价格,存储地点,时间,状态,创建人\n" +
            allCarsData.map(car =>
                `${car.cid},${car.cname},${car.color},${car.price},${car.storage || ''},${car.time || ''},${car.status},${car.creator || ''}`
            ).join("\n");

        // 创建 Blob 对象
        const blob = new Blob([csvContent], {type: "text/csv;charset=utf-8"});
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = "所有车辆数据.csv";
        link.click();
    };

    // 下载全部车辆的TXT文件
    document.getElementById('downloadAllCarsTXT').onclick = function () {
        if (allCarsData.length === 0) {
            alert("请先查询所有车辆！");
            return;
        }

        // 创建 TXT 内容
        const txtContent = allCarsData.map(car =>
            `ID: ${car.cid}, 车名: ${car.cname}, 颜色: ${car.color}, 价格: ${car.price}, 存储地点: ${car.storage || ''}, 时间: ${car.time || ''}, 状态: ${car.status}, 创建人: ${car.creator || ''}`
        ).join("\n");

        // 创建 Blob 对象
        const blob = new Blob([txtContent], {type: "text/plain;charset=utf-8"});
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = "所有车辆数据.txt";
        link.click();
    };


    function fetchUserStats() {
        // 获取普通用户数据
        axios.get('/new/countuser', {
            headers: {'User-Type': 'Admin'}
        })
            .then(response => {
                const normalUsers = response.data;
                document.getElementById('normalUserCount').textContent = normalUsers.length;
                displayUserList(normalUsers, 'normalUserList', false);
            })
            .catch(err => console.error('获取普通用户数据失败:', err));

        // 获取管理员数据
        axios.get('/new/countroot', {
            headers: {'User-Type': 'Admin'}
        })
            .then(response => {
                const adminUsers = response.data;
                document.getElementById('adminUserCount').textContent = adminUsers.length;
                displayUserList(adminUsers, 'adminUserList', true);
            })
            .catch(err => console.error('获取管理员数据失败:', err));
    }

    function displayUserList(users, containerId, isAdmin) {
        const container = document.getElementById(containerId);
        let html = `
        <table class="user-table">
            <thead>
                <tr>
                    <th>用户ID</th>
                    <th>用户名</th>
                    <th>注册时间</th>
                    <th>状态</th>
                </tr>
            </thead>
            <tbody>
    `;

        users.forEach(user => {
            html += `
            <tr>
                <td>${user.uid}</td>
                <td>${user.uname}</td>
                <td>${user.time || '未知'}</td>
                <td>
                    <span class="status-badge ${user.uroot === 1 ? 'status-admin' : 'status-normal'}">
                        ${user.uroot === 1 ? '管理员' : '普通用户'}
                    </span>
                </td>
            </tr>
        `;
        });

        html += `
            </tbody>
        </table>
    `;

        container.innerHTML = html;
    }


    // 新增模态框控制函数
    // 切换注册普通用户模态框显示/隐藏
    function toggleRegisterModal() {
        const registerModal = document.getElementById('registerModal');
        if (registerModal.style.display === 'block') {
            registerModal.style.display = 'none'; // 如果已经显示，则隐藏
        } else {
            registerModal.style.display = 'block'; // 如果未显示，则显示
        }
    }

    // 切换注册管理员用户模态框显示/隐藏
    function toggleRegisterModalroot() {
        const registerModalroot = document.getElementById('registerModalroot');
        if (registerModalroot.style.display === 'block') {
            registerModalroot.style.display = 'none'; // 如果已经显示，则隐藏
        } else {
            registerModalroot.style.display = 'block'; // 如果未显示，则显示
        }
    }

    // 切换管理用户模态框显示/隐藏
    function toggleManageModal() {
        const manageModal = document.getElementById('manageModal');
        if (manageModal.style.display === 'block') {
            manageModal.style.display = 'none'; // 如果已经显示，则隐藏
        } else {
            manageModal.style.display = 'block'; // 如果未显示，则显示
        }
    }

    // 关闭模态框
    function closeModal() {
        document.getElementById('registerModal').style.display = 'none';
    }

    function closeModalroot() {
        document.getElementById('registerModalroot').style.display = 'none';
    }

    function closeManagelroot() {
        document.getElementById('manageModal').style.display = 'none';
    }

    //后台普通用户注册
    function zhuce() {
        var name = $("#unameInput").val();  // 改为获取模态框内的输入
        var pass = $("#upassInput").val();  // 改为获取模态框内的输入
        // 检查用户名和密码是否为空
        if (name === "" || pass === "") {
            alert("账号和密码不能为空！");
            return; // 终止函数执行
        }
        // 检查用户名和密码是否包含空格
        if (name.includes(" ") || pass.includes(" ")) {
            alert("账号和密码不能包含空格！");
            return; // 终止函数执行
        }
        // 检查用户名和密码是否为3-10位的字母或数字
        var pattern = /^[a-zA-Z0-9]{3,10}$/;
        if (!pattern.test(name) || !pattern.test(pass)) {
            alert("账号和密码必须为3-10位的字母或数字！");
            return; // 终止函数执行
        }

        $.ajax({
            type: 'POST',
            url: 'http://127.0.0.1:8080/new/zhuceuser',
            dataType: 'json',
            data: {
                uname: name,
                upass: pass
            },
            success: function (data) {
                if (data == 2) {
                    alert("用户名已存在");
                } else {
                    alert("注册成功");
                    fetchUserStats();
                }
            },
            error: function () {
                alert("无法与数据库取得连接!!!");
            }
        });
    }

    function zhuceroot() {
        var name = $("#rootunameInput").val();  // 改为获取模态框内的输入
        var pass = $("#rootupassInput").val();  // 改为获取模态框内的输入
        // 检查用户名和密码是否为空
        if (name === "" || pass === "") {
            alert("账号和密码不能为空！");
            return; // 终止函数执行
        }
        // 检查用户名和密码是否包含空格
        if (name.includes(" ") || pass.includes(" ")) {
            alert("账号和密码不能包含空格！");
            return; // 终止函数执行
        }
        // 检查用户名和密码是否为3-10位的字母或数字
        var pattern = /^[a-zA-Z0-9]{3,10}$/;
        if (!pattern.test(name) || !pattern.test(pass)) {
            alert("账号和密码必须为3-10位的字母或数字！");
            return; // 终止函数执行
        }

        $.ajax({
            type: 'POST',
            url: 'http://127.0.0.1:8080/new/zhuceroot',
            dataType: 'json',
            data: {
                uname: name,
                upass: pass
            },
            success: function (data) {
                if (data == 2) {
                    alert("用户名已存在");
                } else {
                    alert("注册成功");
                    fetchUserStats();
                }
            },
            error: function () {
                alert("无法与数据库取得连接!!!");
            }
        });
    }


    function updateUser() {
        const userId = $("#userIdInput").val();  // 获取用户ID输入框的值
        const userName = $("#userNameInput").val();  // 获取用户名输入框的值
        const userRoot = $("#userRootSelect").val();  // 获取用户身份选择的值

        // 检查用户ID和用户名是否为空
        if (userId === "" && userName === "") {
            alert("请输入用户ID或用户名！");
            return; // 终止函数执行
        }

        // 检查用户ID和用户名是否包含空格
        if (userId.includes(" ") || userName.includes(" ")) {
            alert("用户ID和用户名不能包含空格！");
            return; // 终止函数执行
        }

        // 发起请求更改用户身份
        $.ajax({
            type: 'POST',
            url: 'http://127.0.0.1:8080/new/updateUser',  // 更改用户身份的接口
            dataType: 'json',
            data: {
                uid: userId,
                uname: userName,
                uroot: userRoot
            },
            success: function (data) {
                if (data === 1) {
                    alert("用户身份更改成功！");
                    fetchUserStats(); // 刷新用户列表
                } else {
                    alert("用户身份更改失败，请检查用户ID和用户名是否正确！");
                }
            },
            error: function () {
                alert("无法与服务器连接，请检查网络或接口地址！");
            }
        });
    }

    function deleteUser() {
        const userId = $("#userIdInput").val();  // 获取用户ID输入框的值
        const userName = $("#userNameInput").val();  // 获取用户名输入框的值

        // 检查用户ID和用户名是否为空
        if (userId === "" || userName === "") {
            alert("用户ID和用户名不能为空！");
            return; // 终止函数执行
        }

        // 检查用户ID和用户名是否包含空格
        if (userId.includes(" ") || userName.includes(" ")) {
            alert("用户ID和用户名不能包含空格！");
            return; // 终止函数执行
        }

        // 确认是否删除用户
        if (confirm(`确定要删除用户ID为${userId}，用户名为${userName}的用户吗？`)) {
            // 发起请求删除用户
            $.ajax({
                type: 'POST',
                url: 'http://127.0.0.1:8080/new/deleteUser',  // 删除用户的接口
                dataType: 'json',
                data: {
                    uid: userId,
                    uname: userName
                },
                success: function (data) {
                    if (data === 1) {
                        alert("用户删除成功！");
                        fetchUserStats(); // 刷新用户列表
                    } else {
                        alert("用户删除失败，请检查用户ID和用户名是否正确！");
                    }
                },
                error: function () {
                    alert("无法与服务器连接，请检查网络或接口地址！");
                }
            });
        }
    }

    //获取页面参数
    function getParameterByName(name, url = window.location.href) {
        name = name.replace(/[\[\]]/g, '\\$&');
        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, ' '));
    }

    const uroot = getParameterByName('uroot');

    var uid = getParameterByName('uid');
    const id = parseInt(uid, 10);

    var name = getParameterByName('uname');

    // 非法登录校验
    if (!name) {
        alert("身份认证失败，请重新登录");
        window.location.href = "login.html";
    }

    document.getElementById('creator').value = name;
    //非法登录校验
    if (uroot == null) {
        alert("身份认证失败，请重新登录");
        window.location.href = "login.html"
    }
    //实现对于的按钮权限
    if (uroot == 0) {
        document.querySelectorAll(".ftype").forEach(function (element) {
            element.style.display = 'none';
        });
        document.querySelectorAll(".ftype1").forEach(function (element) {
            element.style.display = 'none';
        });
    } else {
        document.querySelectorAll(".ftype2").forEach(function (element) {
            element.style.display = 'none';
        });

    }

    // // 获取 <title> 标签
    // const titleElement = document.querySelector("title");
    //
    // if (uroot == 0) {
    //     // 当 uroot == 0 时，设置标题为 "管理员后台"
    //     titleElement.textContent = "管理员系统后台";
    // } else if (uroot == 1) {
    //     // 当 uroot == 1 时，设置标题为 "系统后台"
    //     titleElement.textContent = "管理员后台";
    // } else {
    //     // 其他情况，设置默认标题
    //     titleElement.textContent = "error";
    // }

</script>
</body>
</html>